package com.surface.hao.frame;

import com.surface.hao.component.ScrollPanel;
import com.surface.hao.util.CollectionUtils;
import com.surface.hao.util.ComponentUtils;
import com.surface.hao.util.FileUtils;
import lombok.extern.log4j.Log4j;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 内容搜索面板
 * @Date 2019/12/29
 * @Author songhao
 **/
@Log4j
public class WordSearchPanel {

    static String inputDir = "";
    static ScrollPanel tipArea = null;

    public static JPanel getJpanel(String titleName,JFrame jFrame) {
        JPanel panel = new JPanel();
        //设置布局方式和大小
        panel.setLayout(new BorderLayout(0, 0));
        panel.setSize(800, 600);

        JLabel titleLabel = new JLabel(titleName,JLabel.CENTER);
        titleLabel.setBorder(new EmptyBorder(10, 10, 25, 10));
        titleLabel.setFont(new Font("宋体", Font.BOLD, 24));

        //第一个Panel
        JPanel titlePanel = new JPanel();
        titlePanel.setLayout(new BorderLayout(0, 0));
        panel.add(titlePanel, BorderLayout.NORTH);

        //添加标题信息
        titlePanel.add(titleLabel, BorderLayout.NORTH);

        // 时间戳转换为日期这个Panel
        JPanel timeToDatePanel = getDirPanel(jFrame);
        titlePanel.add(timeToDatePanel, BorderLayout.CENTER);

        // 日期字符串转换为时间戳Panel
        JPanel dateToTimePanel = getWordPanel();
        titlePanel.add(dateToTimePanel, BorderLayout.SOUTH);

        //第二个Panel
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BorderLayout(0, 0));
        panel.add(centerPanel, BorderLayout.CENTER);

        tipArea = new ScrollPanel();
        tipArea.setPreferredSize(new Dimension(200, 350));
        centerPanel.add(tipArea, BorderLayout.CENTER);
        return panel;
    }

    private static JPanel getDirPanel(JFrame frame) {
        JPanel panel_2 = new JPanel();
        FlowLayout flowLayout = (FlowLayout) panel_2.getLayout();
        flowLayout.setAlignment(FlowLayout.LEFT);
        panel_2.setBorder(new TitledBorder(UIManager
                .getBorder("TitledBorder.border"), "查找目录",
                TitledBorder.LEADING, TitledBorder.TOP, null,
                new Color(0, 0, 0)));

        JTextField dir1 = new JTextField();
        dir1.setEditable(false);
        dir1.setEnabled(false);
        dir1.setText("");
        dir1.setFont(new Font("宋体", Font.BOLD, 24));
        dir1.setPreferredSize(new Dimension(600, 40));
        panel_2.add(dir1);

        JButton button_2 = new JButton("选择....");
        button_2.setPreferredSize(new Dimension(100, 40));
        button_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                // 获取源目录
                JFileChooser chooser1 = new JFileChooser();
                //设置可以选择文件或者目录
                chooser1.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                chooser1.setToolTipText("请选择源目录");
                int rt = chooser1.showOpenDialog(frame);
                if (rt == JFileChooser.APPROVE_OPTION) {
                    inputDir = chooser1.getSelectedFile().getPath();
                    log.info("源目录：" + inputDir);
                    dir1.setText(inputDir);
                    dir1.setForeground(new Color(0, 0, 0));
                }
            }
        });
        panel_2.add(button_2);

        return panel_2;
    }

    /**
     * 获取目录的Panel
     * @return
     */
    public static JPanel getWordPanel(){
        JPanel panel_1 = new JPanel();
        FlowLayout flowLayout_1 = (FlowLayout) panel_1.getLayout();
        flowLayout_1.setAlignment(FlowLayout.LEFT);
        panel_1.setBorder(new TitledBorder(UIManager
                .getBorder("TitledBorder.border"), "文件名",
                TitledBorder.LEADING, TitledBorder.TOP, null,
                new Color(0, 0, 0)));

        JTextField dir2 = new JTextField();
        dir2.setText("");
        dir2.setFont(new Font("宋体", Font.BOLD, 24));
        dir2.setPreferredSize(new Dimension(600, 40));
        panel_1.add(dir2);

        JButton button_1 = new JButton("搜索");
        button_1.setPreferredSize(new Dimension(100, 40));
        panel_1.add(button_1);

        JCheckBox c_isSubDir = new JCheckBox("忽略大小写");
        c_isSubDir.setToolTipText("是否忽略大小写？");
        c_isSubDir.setSelected(true);
        panel_1.add(c_isSubDir);

        JCheckBox c_dir = new JCheckBox("完全匹配");
        c_dir.setToolTipText("是否需要完全匹配？");
        c_dir.setSelected(true);
        panel_1.add(c_dir);

        //设置button监控
        button_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String searchWord = dir2.getText();
                log.info("获取文件路径:[" + inputDir + "]," + searchWord);

                // 新启动一个线程进行检索
                new Thread(() -> searchWord(inputDir,searchWord,tipArea)).start();
            }
        });
        return panel_1;
    }

    /**
     * 查询对应的文件内容
     * @param inputDir
     * @param word
     * @param tipArea
     */
    public static void searchWord(String inputDir, String word, ScrollPanel tipArea) {
        if(word == null || "".equals(word.trim())){
            ComponentUtils.setTips(tipArea,"搜索关键词不可以为空!");
            return;
        }

        List<String> allChildPaths = new ArrayList<String>();
        FileUtils.getAllChildPaths(inputDir, allChildPaths,false);

        for (String childPath : allChildPaths) {
            List<String> resultList = searchWordByPath(childPath, word);
            if (resultList.size() > 0) {
                //在输入框中显示内容
                tipArea.setText(tipArea.getText() + CollectionUtils.join(resultList, "\n"));
            }
        }
    }

    /**
     * 查询单词
     *
     * @param inputDir
     * @param word
     */
    public static List<String> searchWordByPath(String inputDir, String word) {
        List<String> resultList = new ArrayList<String>();
        BufferedReader reader = null;
        try {
            reader = FileUtils.getReader(inputDir);
            String tempLine = null;
            int lineIndex = 0;
            while ((tempLine = reader.readLine()) != null) {
                lineIndex++;
                System.out.println(tempLine + "---" + word);
                if (tempLine.contains(word)) {
                    resultList.add("在文件:[" + inputDir + "]的" + lineIndex + "行:" + tempLine);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            FileUtils.closeReader(reader);
        }
        return resultList;
    }

    static class MyTextArea extends JPanel {

        private JTextArea text = new JTextArea();
        private JScrollPane scrollPanel = new JScrollPane(text);

        public MyTextArea() {
            this.setLayout(new BorderLayout());

            text.setFont(new Font("宋体", Font.BOLD, 16));
            scrollPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); //设置水平滚动框一直显示
            scrollPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);//设置垂直滚动框一直显示
            this.add(scrollPanel, BorderLayout.CENTER);
        }

        public String getText(){
            return this.text.getText();
        }

        /**
         * 给textarea设置内容
         * @param content
         */
        public void setText(String content){
            text.setText(content);
        }
    }
}
